﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 图片裁剪压缩工具
{
    internal class RecyclableMemoryStream : Stream
    {
        private readonly byte[] _data;
        private int _maxOffset;
        private int _currentOffset;
        public RecyclableMemoryStream(int capacity)
        {
            _data = new byte[capacity];
            Reset();
        }
        public override bool CanRead => false;

        public override bool CanSeek => false;

        public override bool CanWrite => true;

        public override long Length => _maxOffset;

        public override long Position 
        {
            get => _currentOffset;
            set => _currentOffset =(int) value;
        }

        public override void Flush()
        {

        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }

        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (_currentOffset + count <= _data.Length)
            {
                Array.Copy(buffer, offset, _data, _currentOffset, count);
                _currentOffset += count;
                _maxOffset = Math.Max(_currentOffset, _maxOffset);
            }
            else throw new OutOfMemoryException();
        }
        public void Reset()
        {
            _currentOffset = 0;
            _maxOffset = 0;
        }
        public void Save(string fileName)
        {
            using (var stream = File.Create(fileName))
            {
                stream.Write(_data, 0, _maxOffset);
            }
        }
    }
}
